package com.letu.aopcache.aspectj;

import com.letu.annotation.annotation.cache.Cache;
import com.letu.aopcache.handler.CacheHandler;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;

import java.lang.reflect.Method;

/**
 * 使用Aspectj 实现AOP拦截 注意：拦截器不能有相同名字的Method
 * 拦截的入口
 * 111111111112222222
 *
 */
@Aspect
//@Component
@Order(2)
@Slf4j
public class AspectjAopInterceptor {

    private final CacheHandler cacheHandler;


    public AspectjAopInterceptor(CacheHandler cacheHandler) {
        this.cacheHandler = cacheHandler;
    }

    public Object checkAndProceed(ProceedingJoinPoint pjp) throws Throwable {
        Signature signature = pjp.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method.isAnnotationPresent(Cache.class)) {
            Cache cache = method.getAnnotation(Cache.class);// method.getAnnotationsByType(Cache.class)[0];
            return this.proceed(pjp, cache);
        }

        try {
            return pjp.proceed();
        } catch (Throwable e) {
            throw e;
        }
    }



    public Object proceed(ProceedingJoinPoint aopProxyChain, Cache cache) throws Throwable {
        return cacheHandler.proceed(new AspectjCacheAopProxyChain(aopProxyChain), cache);
    }


    public CacheHandler getCacheHandler() {
        return cacheHandler;
    }

}
